import 'dart:async';
import 'package:flutter/material.dart';
import 'package:grint/utils/whisper.dart';
import 'package:grint/utils/local_store.dart';

class TimeReminderService {
  static final TimeReminderService _instance = TimeReminderService._internal();
  factory TimeReminderService() => _instance;
  TimeReminderService._internal();

  Timer? _timeCheckTimer;
  bool _morningSwitch = false;
  bool _eveningSwitch = false;
  TimeOfDay _morningTime = const TimeOfDay(hour: 8, minute: 0);
  TimeOfDay _eveningTime = const TimeOfDay(hour: 19, minute: 0);

  void startTimeCheck() {
    _timeCheckTimer?.cancel();
    _loadSettings();
    _timeCheckTimer = Timer.periodic(const Duration(minutes: 1), (timer) {
      _checkTimeAndNotify();
    });
  }

  Future<void> _loadSettings() async {
    await LocalStore().init();

    // 加载开关状态
    _morningSwitch = LocalStore().getFlagValue(
      'morning_switch',
      defaultValue: false,
    );
    _eveningSwitch = LocalStore().getFlagValue(
      'evening_switch',
      defaultValue: false,
    );

    // 加载时间设置
    final morningHour = LocalStore().getNumberValue(
      'morning_hour',
      defaultValue: 8,
    );
    final morningMinute = LocalStore().getNumberValue(
      'morning_minute',
      defaultValue: 0,
    );
    _morningTime = TimeOfDay(hour: morningHour, minute: morningMinute);

    final eveningHour = LocalStore().getNumberValue(
      'evening_hour',
      defaultValue: 19,
    );
    final eveningMinute = LocalStore().getNumberValue(
      'evening_minute',
      defaultValue: 0,
    );
    _eveningTime = TimeOfDay(hour: eveningHour, minute: eveningMinute);
  }

  void stopTimeCheck() {
    _timeCheckTimer?.cancel();
    _timeCheckTimer = null;
  }

  void updateMorningReminder(bool enabled, TimeOfDay time) {
    _morningSwitch = enabled;
    _morningTime = time;
  }

  void updateEveningReminder(bool enabled, TimeOfDay time) {
    _eveningSwitch = enabled;
    _eveningTime = time;
  }

  void _checkTimeAndNotify() {
    final now = DateTime.now();
    final currentTime = TimeOfDay(hour: now.hour, minute: now.minute);

    // 检查早上时间
    if (_morningSwitch &&
        currentTime.hour == _morningTime.hour &&
        currentTime.minute == _morningTime.minute) {
      Whisper.breath('Good morning! Time to brush your teeth! 🦷');
    }

    // 检查晚上时间
    if (_eveningSwitch &&
        currentTime.hour == _eveningTime.hour &&
        currentTime.minute == _eveningTime.minute) {
      Whisper.breath('Good evening! Time to brush your teeth! 🦷');
    }
  }

  void dispose() {
    stopTimeCheck();
  }
}
